package com.joehaivo.hweather.Presenter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.joehaivo.hweather.Model.CaiyunForeBean;
import com.joehaivo.hweather.Model.CaiyunNowBean;
import com.joehaivo.hweather.Model.HefengAQIBean;
import com.joehaivo.hweather.Model.HefengForeBean;
import com.joehaivo.hweather.Model.HefengNowBean;
import com.joehaivo.hweather.Model.HefengSuggestionBean;
import com.joehaivo.hweather.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Forecast{
    private static final int TAG_SUCCESS_FLAG = 0;
    private static final int TAG_DATE = 1;
    private static final int TAG_FORE_CONDITION = 2;
    private static final int TAG_NOW_CONDITION = 3;
    private static final int TAG_HIGHTMP = 4;
    private static final int TAG_LOWTMP = 5;
    private static final int TAG_NOW_TMP = 6;
    private static final int TAG_IMAGE_DRAW = 7;
    private static final int TAG_HOURLYDESCRIPTION = 8;
    private static final int TAG_LIST = 9;
    private static final int TAG_FORE_CODE = 10;
    private static final int TAG_FORE_HOURLY = 11;
    private static final int TAG_SUGGESTION = 12;
    private static final int TAG_HEFENG_AQI = 13;
    private Context context;
    private Handler mHandler;
    String TAG = "TAG";
    private final OkHttpClient client = new OkHttpClient();

    public Forecast(Context context,Handler mainHandler){
        mHandler = mainHandler;
        this.context = context;
    }
    public void getCaiyunNow(double longitude, double latitude){
        final String basicUrl = "https://api.caiyunapp.com/v2/7xJkeOW5-lexk1l5/";
        final String endUrl = "/forecast.json";
        Request request = new Request.Builder()
                .url(basicUrl+longitude+","+latitude+endUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.obtainMessage(TAG_SUCCESS_FLAG,"Failed").sendToTarget();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                Gson gson = new Gson();
                CaiyunNowBean caiyunNowBean = gson.fromJson(response.body().string(),CaiyunNowBean.class);
                if ("ok".equals(caiyunNowBean.getStatus())){
                    CaiyunNowBean.ResultBean caiyunRealtimeResult = caiyunNowBean.getResult();
                    double realtimeTmp = caiyunRealtimeResult.getTemperature();
                    Log.d(TAG, "realtime: "+realtimeTmp);
                    mHandler.obtainMessage(2,realtimeTmp).sendToTarget();
                    String realtimeSkycon = caiyunRealtimeResult.getSkycon();
                    if ("CLOUDY".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3,"阴").sendToTarget();
                    }else if ("RAIN".equals(realtimeSkycon)) {
                        mHandler.obtainMessage(3, "雨").sendToTarget();
                    }else if ("CLEAR_NIGHT".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "晴").sendToTarget();
                    }else if ("CLEAR_DAY".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "晴").sendToTarget();
                    }else if ("PARTLY_CLOUDY_DAY".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "多云").sendToTarget();
                    }else if ("PARTLY_CLOUDY_NIGHT".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "多云").sendToTarget();
                    }else if ("SNOW".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "雪").sendToTarget();
                    }else if ("WIND".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "风").sendToTarget();
                    }else if ("FOG".equals(realtimeSkycon)){
                        mHandler.obtainMessage(3, "雾").sendToTarget();
                    }
                }
            }
        });
    }
    public void getCaiyunFore(double longitude,double latitude){
        final String basicUrl = "https://api.caiyunapp.com/v2/7xJkeOW5-lexk1l5/";
        final String endUrl = "/forecast.json";
        Request request = new Request.Builder()
                .url(basicUrl+longitude+","+latitude+endUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                Gson gson = new Gson();
                CaiyunForeBean caiyunForeBean = gson.fromJson(response.body().string(),CaiyunForeBean.class);
                String status = caiyunForeBean.getStatus();
                if (status.equals("ok")){
                    CaiyunForeBean.ResultBean resultsBean = caiyunForeBean.getResult();
                    CaiyunForeBean.ResultBean.HourlyBean hourlyBean = resultsBean.getHourly();
                    String hourlyDescription = hourlyBean.getDescription();
                    List<CaiyunForeBean.ResultBean.HourlyBean.SkyconBean> skyconBeanList = hourlyBean.getSkycon();
                    List<CaiyunForeBean.ResultBean.HourlyBean.TemperatureBean> temperatureBeanList = hourlyBean.getTemperature();
                    List<Map<String,Object>> hourlist = new ArrayList<Map<String, Object>>();
                    Map<String,Object> hourMap;
                    List<CaiyunForeBean.ResultBean.HourlyBean.PrecipitationBean> precipitationBeanList = hourlyBean.getPrecipitation();
                    int hours = 0;
                    while(hours<24){
                        hourMap = new HashMap<>();
                        CaiyunForeBean.ResultBean.HourlyBean.SkyconBean skyconBean = skyconBeanList.get(hours);
                        String time = skyconBean.getDatetime();
                        hourMap.put("time",time.substring(11)); //未来24小时每小时时间
                        String hourConditon = "N/A";
                        CaiyunForeBean.ResultBean.HourlyBean.PrecipitationBean precipitationBean = precipitationBeanList.get(hours);
                        Drawable drawable = null;
                        if (skyconBean.getValue().equals("CLOUDY")){
                            hourConditon = "阴";
                            drawable = context.getDrawable(R.drawable.over_cast);
                        }else if (skyconBean.getValue().equals("CLEAR_NIGHT")){
                            hourConditon = "晴夜";
                            drawable = context.getDrawable(R.drawable.sunny_night);
                        }else if (skyconBean.getValue().equals("CLEAR_DAY")){
                            hourConditon = "晴";
                            drawable = context.getDrawable(R.drawable.sunny);
                        }else if (skyconBean.getValue().equals("PARTLY_CLOUDY_DAY")){
                            hourConditon = "多云";
                            drawable = context.getDrawable(R.drawable.cloudy);
                        }else if (skyconBean.getValue().equals("PARTLY_CLOUDY_NIGHT")){
                            hourConditon = "多云";
                            drawable = context.getDrawable(R.drawable.cloudy);
                        }else if (skyconBean.getValue().equals("SNOW")){
                            hourConditon = "雪";
                            drawable = context.getDrawable(R.drawable.heavy_snow);
                        }else if (skyconBean.getValue().equals("WIND")){
                            hourConditon = "风";
                            drawable = context.getDrawable(R.drawable.wind);
                        }else if (skyconBean.getValue().equals("FOG")){
                            hourConditon = "雾";
                            drawable = context.getDrawable(R.drawable.fog);
                        }else if (skyconBean.getValue().equals("RAIN")){
                            if (precipitationBean.getValue()<=0.9){
                                hourConditon = "小雨";
                                drawable = context.getDrawable(R.drawable.light_rain);
                            } else if (precipitationBean.getValue() > 0.9 && precipitationBean.getValue() <= 2.87) {
                                hourConditon = "中雨";
                                drawable = context.getDrawable(R.drawable.mid_rain);
                            }else if (precipitationBean.getValue() > 2.87){
                                hourConditon = "大雨";
                                drawable = context.getDrawable(R.drawable.heavy_rain);
                            }
                        }
                        hourMap.put("hourConditon",hourConditon); //24时天气
                        hourMap.put("hourImage",drawable);//图片
                        CaiyunForeBean.ResultBean.HourlyBean.TemperatureBean temperatureBean = temperatureBeanList.get(hours);
                        double hourTmp = temperatureBean.getValue();
                        hourMap.put("hourTmp",Math.round(hourTmp));//温度
                        hourlist.add(hourMap);
                        hours++;
                    }
                    mHandler.obtainMessage(TAG_FORE_HOURLY,hourlist).sendToTarget();
                    mHandler.obtainMessage(TAG_HOURLYDESCRIPTION,hourlyDescription).sendToTarget();
                }
            }
        });
    }
    public void getHefengFore(String city){
        final String basicUrl = "https://free-api.heweather.com/v5/forecast?city=";
        final String keyUrl = "&key=bbeef92e1fe94133b1c298024e7629f5";
        Request request = new Request.Builder()
                .url(basicUrl+city+keyUrl)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                Gson gson = new Gson();
                HefengForeBean hefeng = gson.fromJson(response.body().string(), HefengForeBean.class);
                List<HefengForeBean.HeWeather5Bean> heWeather5List = hefeng.getHeWeather5();
                HefengForeBean.HeWeather5Bean he5Bean = heWeather5List.get(0);
                List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
                int yy = 0;
                while (yy < 7) {
                    List<HefengForeBean.HeWeather5Bean.DailyForecastBean> dailyBean = he5Bean.getDaily_forecast();
                    HefengForeBean.HeWeather5Bean.DailyForecastBean daily = dailyBean.get(yy);
                    HefengForeBean.HeWeather5Bean.DailyForecastBean.CondBean cond = daily.getCond();
                    Map<String,Object> map = new HashMap<>();
                    if (yy == 0){
                        map.put("DATE","今天");
                        mHandler.obtainMessage(TAG_DATE,"今天");
                    }else if (yy == 1){
                        map.put("DATE","明天");
                        mHandler.obtainMessage(TAG_DATE,"明天");
                    }else{
                        map.put("DATE",daily.getDate().substring(5));
                        mHandler.obtainMessage(TAG_DATE,daily.getDate().substring(5));
                    }
                    //天气状况
                    String txt = cond.getTxt_d();
                    if (txt.equals("晴间多云")){
                        map.put("FORE_CONDITION","多云");
                    }else {
                        map.put("FORE_CONDITION",txt);
                    }
                    mHandler.obtainMessage(TAG_FORE_CONDITION, txt);
                    String code = cond.getCode_d();
                    mHandler.obtainMessage(TAG_FORE_CODE,code);
                    Drawable draw = null;
                    switch (Integer.valueOf(code)){
                        case 100: draw = context.getDrawable(R.drawable.sunny);break;
                        case 101: draw = context.getDrawable(R.drawable.cloudy);break;
                        case 103: draw = context.getDrawable(R.drawable.cloudy);break;
                        case 104: draw = context.getDrawable(R.drawable.over_cast);break;
                        case 300: draw = context.getDrawable(R.drawable.shower);break;
                        case 305: draw = context.getDrawable(R.drawable.light_rain);break;
                        case 306: draw = context.getDrawable(R.drawable.mid_rain);break;
                    }
                    map.put("IMAGE_DRAW",draw);
                    mHandler.obtainMessage(TAG_IMAGE_DRAW,draw);
                    HefengForeBean.HeWeather5Bean.DailyForecastBean.TmpBean tmp = daily.getTmp();
                    String tmpHigh = tmp.getMax() + "°";
                    map.put("HIGH_TMP",tmpHigh);
                    mHandler.obtainMessage(TAG_HIGHTMP, tmpHigh);
                    String tmpLow = tmp.getMin() + "°";
                    map.put("LOW_TMP",tmpLow);
                    mHandler.obtainMessage(TAG_LOWTMP, tmpLow);
                    list.add(map);
                    yy++;
                }
                mHandler.obtainMessage(TAG_LIST,list).sendToTarget();
                mHandler.obtainMessage(TAG_SUCCESS_FLAG,"Succeed").sendToTarget();
            }
        });
    }
    public void getHefengNow(String city){
        final String basicUrl = "https://free-api.heweather.com/v5/now?city=";
        final String keyUrl = "&key=bbeef92e1fe94133b1c298024e7629f5";
        Request okRequest = new Request.Builder()
                .url(basicUrl+city+keyUrl)
                .build();
        client.newCall(okRequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                Gson gson = new Gson();
                HefengNowBean Bean = gson.fromJson(response.body().string(),HefengNowBean.class);
                List<HefengNowBean.HeWeather5Bean> heWeather5Beanlist = Bean.getHeWeather5();
                HefengNowBean.HeWeather5Bean  heWeather5Bean = heWeather5Beanlist.get(0);
                HefengNowBean.HeWeather5Bean.NowBean nowBean = heWeather5Bean.getNow();
                int nowTmp = nowBean.getTmp();
                mHandler.obtainMessage(TAG_NOW_TMP,nowTmp).sendToTarget();
                HefengNowBean.HeWeather5Bean.NowBean.CondBean condBean= nowBean.getCond();
                String nowTxt = condBean.getTxt();
                mHandler.obtainMessage(TAG_NOW_CONDITION,nowTxt).sendToTarget();
            }
        });
    }
    public void getHefengSuggestion(String city){
        final String basicUrl = "https://free-api.heweather.com/v5/suggestion?city=";
        final String keyUrl = "&key=bbeef92e1fe94133b1c298024e7629f5";
        Request okRequest = new Request.Builder()
                .url(basicUrl+city+keyUrl)
                .build();
        client.newCall(okRequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                HefengSuggestionBean bean = gson.fromJson(response.body().string(), HefengSuggestionBean.class);
                List<HefengSuggestionBean.HeWeather5Bean> heWeather5Beenlist = bean.getHeWeather5();
                HefengSuggestionBean.HeWeather5Bean heWeather5Bean = heWeather5Beenlist.get(0);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean suggestionBean = heWeather5Bean.getSuggestion();
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.AirBean airBean = suggestionBean.getAir();
                List<Map<String,Object>> listSuggestion = new ArrayList<Map<String, Object>>();
                Map<String,Object> mapSuggestion = new HashMap<String, Object>();
                Drawable drawable = context.getDrawable(R.drawable.air);
                mapSuggestion.put("live",drawable);
                String brf = airBean.getBrf();
                mapSuggestion.put("field","空气指数  "+brf);
                String txt = airBean.getTxt();
                mapSuggestion.put("fieldTxt",txt);
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.comfort);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.ComfBean comfBean = suggestionBean.getComf();
                brf = comfBean.getBrf();
                mapSuggestion.put("field","舒适度  "+brf);
                txt = comfBean.getTxt();
                mapSuggestion.put("fieldTxt",txt);
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.clothes);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.DrsgBean drsgBean = suggestionBean.getDrsg();
                mapSuggestion.put("field","穿衣指数  "+drsgBean.getBrf());
                mapSuggestion.put("fieldTxt",drsgBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.uv);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.UvBean uvBean = suggestionBean.getUv();
                mapSuggestion.put("field","紫外线强度  "+uvBean.getBrf());
                mapSuggestion.put("fieldTxt",uvBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.risk);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.FluBean fluBean = suggestionBean.getFlu();
                mapSuggestion.put("field","感冒指数  "+fluBean.getBrf());
                mapSuggestion.put("fieldTxt",fluBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.sport);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.SportBean sportBean = suggestionBean.getSport();
                mapSuggestion.put("field","运动指数  "+sportBean.getBrf());
                mapSuggestion.put("fieldTxt",sportBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.travel);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.TravBean travBean = suggestionBean.getTrav();
                mapSuggestion.put("field","旅游指数  "+travBean.getBrf());
                mapSuggestion.put("fieldTxt",travBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mapSuggestion = new HashMap<String, Object>();
                drawable = context.getDrawable(R.drawable.wash_car);
                mapSuggestion.put("live",drawable);
                HefengSuggestionBean.HeWeather5Bean.SuggestionBean.CwBean cwBean = suggestionBean.getCw();
                mapSuggestion.put("field","洗车指数  "+cwBean.getBrf());
                mapSuggestion.put("fieldTxt",cwBean.getTxt());
                listSuggestion.add(mapSuggestion);

                mHandler.obtainMessage(TAG_SUGGESTION,listSuggestion).sendToTarget();
            }
        });
    }
    public void getHefengAQI(String city){
        final String basicUrl = "https://free-api.heweather.com/v5/aqi?city=";
        final String keyUrl = "&key=bbeef92e1fe94133b1c298024e7629f5";
        Request okRequest = new Request.Builder()
                .url(basicUrl+city+keyUrl)
                .build();
        client.newCall(okRequest).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                HefengAQIBean bean = gson.fromJson(response.body().string(), HefengAQIBean.class);
                List<HefengAQIBean.HeWeather5Bean> heWeather5BeanList = bean.getHeWeather5();
                HefengAQIBean.HeWeather5Bean heWeather5Bean = heWeather5BeanList.get(0);
                HefengAQIBean.HeWeather5Bean.AqiBean aqiBean = heWeather5Bean.getAqi();
                HefengAQIBean.HeWeather5Bean.AqiBean.CityBean cityBean = aqiBean.getCity();
                mHandler.obtainMessage(TAG_HEFENG_AQI,cityBean.getAqi()+" "+cityBean.getQlty()).sendToTarget();
            }
        });
    }
}
